package org.zjt.chapter1.rxnetty.proxy;

import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.server.HttpServer;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import rx.Observable;
import rx.observables.BlockingObservable;

import java.util.Iterator;
import java.util.Map;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-22 下午1:04
 * @see
 */
@Slf4j
public class ProxyHttpServerTest {

    @Test
    public void server() {
        int serverPort = startTargetServer();

        HttpClient<ByteBuf, ByteBuf> httpClient = HttpClient.newClient("localhost", serverPort);

        HttpServer.newServer(8080).start((req,res) ->{

            HttpClientRequest<ByteBuf, ByteBuf> request = httpClient.createRequest(req.getHttpMethod(), req.getUri());
            Iterator<Map.Entry<CharSequence, CharSequence>> entryIterator = req.headerIterator();

            for (;entryIterator.hasNext();){
                Map.Entry<CharSequence, CharSequence> next = entryIterator.next();
                request.addHeader(next.getKey(),next.getValue());
            }

            return request.writeContent(req.getContent()).flatMap(response -> {

                Iterator<Map.Entry<CharSequence, CharSequence>> entryIterator1 = response.headerIterator();
                for (;entryIterator1.hasNext();){
                    Map.Entry<CharSequence, CharSequence> next = entryIterator1.next();
                    res.addHeader(next.getKey(),next.getValue());
                }

                return res.write(response.getContent());
            });
        }).awaitShutdown();
    }



    public int startTargetServer(){
        HttpServer<ByteBuf, ByteBuf> server = HttpServer.newServer().start((req, resq) -> {
            log.info(req.getUri());
            return resq.writeString(Observable.just("hello world"));
        });

        return server.getServerPort();
    }
}
